<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>棉花公证检验条码打印系统</title>
    <!-- 网络依赖 后续转化为本地       
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    -->
    <!-- 本地依赖 -->
    <link rel="stylesheet" href="./css/all.min.css">
    <script src="./js/JsBarcode.all.min.js"></script>
    <script src="./js/jspdf.umd.min.js"></script>
    <script src="./js/html2canvas.min.js"></script>
    <!-- TSC打印机驱动 -->
    <script src="./assert/js/base64.js"></script>
    <script src="./assert/js/TSC.js"></script>
    <link rel="stylesheet" href="./css/index.css">
</head>
<body>
    <!-- 表单页面 -->
    <div class="container" id="formContainer">
        <header>
            <div style="display: flex; align-items: center; justify-content: space-between;">
                <button onclick="window.location.href='index.html'" class="btn btn-secondary" style="background: rgba(255,255,255,0.2); border: 1px solid rgba(255,255,255,0.3); color: white; padding: 8px 15px; font-size: 14px;">
                    <i class="fas fa-home"></i> 返回首页
                </button>
                <h1><i class="fas fa-barcode"></i> 棉花公证检验条码打印系统</h1>
                <div style="width: 100px;"></div>
            </div>
        </header>

        <main>
            <form class="form-container" id="barcodeForm">
                <div class="form-sections-container">
                    <div class="form-section">
                        <h2><i class="fas fa-print"></i> 打印信息</h2>
                        <div class="form-group">
                            <label for="inspection_type"><i class="fas fa-clipboard-check"></i> 公证检验类型:</label>
                            <select id="inspection_type" name="inspection_type">
                                <option value="经营性棉花公证检验">经营性棉花公证检验·18位条码</option>
                                <option value="期货交割棉公证检验">期货交割棉公证检验·19位条码</option>
                                <option value="交易撮合棉公证检验">交易撮合棉公证检验·20位条码</option>
                                <option value="其他类型公证检验">棉花粘性(含糖)检测方法试点检验·21位条码</option>
                            </select>
                        </div>
                        
                        <div class="form-row">
                            <div class="form-group">
                                <label for="batch_number"><i class="fas fa-hashtag"></i> 批号:</label>
                                <input type="text" id="batch_number" name="batch_number" value="123" required>
                            </div>
                            <div class="form-group">
                                <label for="sample_number"><i class="fas fa-vial"></i> 样品号:</label>
                                <input type="text" id="sample_number" name="sample_number" value="345" required>
                            </div>
                        </div>
                        
                        <div class="form-row">
                            <div class="form-group">
                                <label for="origin"><i class="fas fa-map-marker-alt"></i> 产地:</label>
                                <input type="text" id="origin" name="origin" value="河南郑州" required>
                            </div>
                            <div class="form-group">
                                <label for="package_number"><i class="fas fa-box"></i> 包号:</label>
                                <input type="text" id="package_number" name="package_number" value="332" required>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="sampling_date"><i class="fas fa-calendar-alt"></i> 抽样日期:</label>
                            <input type="date" id="sampling_date" name="sampling_date" value="2025-09-18" required>
                        </div>
                        <div class="form-group" id="detection_type_group" style="display: none;">
                            <label><i class="fas fa-flask"></i> 检测类型:</label>
                            <div class="checkbox-group">
                                <div class="checkbox-item">
                                    <input type="checkbox" id="detection_type_1" name="detection_types" value="热滚筒法">
                                    <label for="detection_type_1">1. 热滚筒法（01）</label>
                                </div>
                                <div class="checkbox-item">
                                    <input type="checkbox" id="detection_type_2" name="detection_types" value="分光光度法">
                                    <label for="detection_type_2">2. 分光光度法（02）</label>
                                </div>
                                <div class="checkbox-item">
                                    <input type="checkbox" id="detection_type_3" name="detection_types" value="色卡比色法">
                                    <label for="detection_type_3">3. 色卡比色法（03）</label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-section">
                        <h2><i class="fas fa-barcode"></i> 条码设置</h2>
                        <div class="form-group">
                            <label for="start_number"><i class="fas fa-sort-numeric-up"></i> 起始编号: <span id="length_info">(18位)</span></label>
                            <input type="text" id="start_number" name="start_number" value="123456789123456789" required>
                            <span id="current_length" class="length-indicator">当前长度: 18/18</span>
                            <div id="special_remark" class="special-remark" style="display: none;">
                                <i class="fas fa-info-circle"></i> 按照试验内容勾选检测类型选项，录入后19位即可，条码会自动根据第一个检测类型在编码前增加两位
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="barcode_count"><i class="fas fa-list-ol"></i> 条码数量:</label>
                            <input type="number" id="barcode_count" name="barcode_count" min="1" max="1000" value="10" required>
                            <span class="length-indicator">支持A4多页打印和条码标签打印</span>
                        </div>
                    </div>
                </div>

                <div class="form-actions">
                    <button type="reset" class="btn btn-secondary"><i class="fas fa-redo"></i> 重置</button>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-print"></i> 生成条码</button>
                </div>
            </form>
        </main>

        <footer>
            <p>棉花公证检验条码打印系统 &copy; 2025</p>
        </footer>
    </div>

    <!-- 打印页面 -->
    <div class="print-container" id="printContainer">
        <div class="print-actions">
            <div class="print-mode-selector">
                <label class="print-mode-label">打印方式:</label>
                <button onclick="switchPrintMode('a4')" class="btn btn-secondary print-mode-btn active" id="a4ModeBtn">
                    <i class="fas fa-file-alt"></i> A4打印
                </button>
                <button onclick="switchPrintMode('tsc')" class="btn btn-secondary print-mode-btn" id="tscModeBtn">
                    <i class="fas fa-barcode"></i> TSC打印机 (80×45mm)
                </button>
                <div class="print-buttons">
                    <button onclick="backToForm()" class="btn">
                        <i class="fas fa-arrow-left"></i> 返回修改
                    </button>
                </div>
            </div>
            <div id="a4PreviewHeader" style="text-align: center; padding: 20px; background: #f8f9fc; border-radius: 8px; margin-bottom: 20px;">
                <h3>A4打印预览</h3>
                <p>以下是条码的A4打印预览效果，每页包含10个条码标签</p>
                <div style="margin: 15px 0;display: flex;justify-content: center;">
                    <button onclick="window.print()" class="btn btn-primary" style="margin: 0 10px;">
                        <i class="fas fa-print"></i> 打印
                    </button>
                </div>
            </div>
        </div>

        <div id="printContent">
            <!-- 动态生成打印内容 -->
        </div>
    </div>

    <script>
        // 全局变量
        let currentFormData = {};
        let barcodeImages = [];
        let currentPrintMode = 'a4'; // 默认A4打印模式
        
        // TSC打印机连接变量
        var url = "ws://127.0.0.1:8888";
        var usb_printers = [];
        var driver_printers = [];
        var selectedPrinter = null;
        var selectedConnectionType = 'usb'; // usb, network, driver

        // 定义每种类型的长度限制
        const lengthLimits = {
            '经营性棉花公证检验': 18,
            '期货交割棉公证检验': 19,
            '交易撮合棉公证检验': 20,
            '其他类型公证检验': 19
        };

        // 检测类型对应的两位数字前缀
        const detectionTypePrefixes = {
            '热滚筒法': '01',
            '分光光度法': '02',
            '色卡比色法': '03'
        };

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            const inspectionType = document.getElementById('inspection_type');
            const startNumber = document.getElementById('start_number');
            const lengthInfo = document.getElementById('length_info');
            const currentLength = document.getElementById('current_length');
            
            // 更新长度显示和验证
            function updateLengthValidation() {
                const selectedType = inspectionType.value;
                const limit = lengthLimits[selectedType];
                const currentValue = startNumber.value;
                
                // 更新限制信息
                lengthInfo.textContent = `(${limit}位)`;
                
                // 设置输入框的maxlength属性
                startNumber.maxLength = limit;
                
                // 更新当前长度显示
                currentLength.textContent = `当前长度: ${currentValue.length}/${limit}`;
                
                // 验证长度并设置相应的样式和错误信息
                if (currentValue.length > limit) {
                    // 超过限制
                    currentLength.classList.add('warning');
                    startNumber.setCustomValidity(`输入长度不能超过${limit}位`);
                } else if (currentValue.length !== limit && currentValue.length > 0) {
                    // 长度不匹配且不为空
                    currentLength.classList.add('warning');
                    startNumber.setCustomValidity(`输入长度必须为${limit}位，当前长度为${currentValue.length}位`);
                } else {
                    // 长度正确或为空
                    currentLength.classList.remove('warning');
                    startNumber.setCustomValidity('');
                }
            }
            
            // 监听选择框变化
            inspectionType.addEventListener('change', function() {
                updateLengthValidation();
                updateDetectionTypeVisibility();
                updateSpecialRemarkVisibility();
                updateBarcodeCountVisibility();
            });
            
            // 监听输入框变化
            startNumber.addEventListener('input', updateLengthValidation);
            
            // 初始化验证
            updateLengthValidation();
            updateDetectionTypeVisibility();
            updateSpecialRemarkVisibility();
            updateBarcodeCountVisibility();

            // 表单提交处理
            document.getElementById('barcodeForm').addEventListener('submit', handleFormSubmit);
            
            // 表单重置处理
            document.getElementById('barcodeForm').addEventListener('reset', function() {
                // 重置后延迟执行，确保表单值已经重置
                setTimeout(() => {
                    updateLengthValidation();
                    updateDetectionTypeVisibility();
                    updateSpecialRemarkVisibility();
                    updateBarcodeCountVisibility();
                }, 0);
            });
            
            // 初始化TSC打印机连接
            initTSCConnection();
        });

        // 更新检测类型复选框显示状态
        function updateDetectionTypeVisibility() {
            const inspectionType = document.getElementById('inspection_type');
            const detectionTypeGroup = document.getElementById('detection_type_group');
            
            // 只有当选择"其他类型公证检验"时才显示检测类型复选框
            if (inspectionType.value === '其他类型公证检验') {
                detectionTypeGroup.style.display = 'block';
            } else {
                detectionTypeGroup.style.display = 'none';
                // 隐藏时清空所有复选框的选择
                const checkboxes = detectionTypeGroup.querySelectorAll('input[type="checkbox"]');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = false;
                });
            }
        }

        // 更新特殊备注显示状态
        function updateSpecialRemarkVisibility() {
            const inspectionType = document.getElementById('inspection_type');
            const specialRemark = document.getElementById('special_remark');
            
            // 只有当选择"其他类型公证检验"时才显示特殊备注
            if (inspectionType.value === '其他类型公证检验') {
                specialRemark.style.display = 'block';
            } else {
                specialRemark.style.display = 'none';
            }
        }

        // 更新条码数量输入框状态
        function updateBarcodeCountVisibility() {
            const inspectionType = document.getElementById('inspection_type');
            const barcodeCount = document.getElementById('barcode_count');
            
            // 如果选择"其他类型公证检验"，条码数量固定为1且禁用
            if (inspectionType.value === '其他类型公证检验') {
                barcodeCount.value = '1';
                barcodeCount.disabled = true;
            } else {
                barcodeCount.disabled = false;
            }
        }

        // 处理表单提交
        function handleFormSubmit(e) {
            e.preventDefault();
            
            const formData = new FormData(e.target);
            currentFormData = Object.fromEntries(formData.entries());
            
                        // 验证起始编号长度
            const selectedType = currentFormData.inspection_type;
            const limit = lengthLimits[selectedType];
            const currentValue = currentFormData.start_number;
            
            // 检查是否超过限制
            if (currentValue.length > limit) {
                alert(`起始编号长度不能超过${limit}位`);
                return;
            }

            // 检查是否达到要求长度
            if (currentValue.length !== limit) {
                alert(`起始编号长度必须为${limit}位，当前长度为${currentValue.length}位`);
                return;
            }

            // 如果是其他类型公证检验，验证检测类型选择
            if (selectedType === '其他类型公证检验') {
                const detectionTypes = formData.getAll('detection_types');
                currentFormData.detection_types = detectionTypes;

                // 验证至少选择一个检测类型
                if (detectionTypes.length === 0) {
                    alert('请至少选择一个检测类型');
                    return;
                }
            }



            // 生成条码
            generateBarcodes();
        }
        // 字符串数字递增函数，避免大数字精度丢失
        function incrementStringNumber(str, increment) {
            // 将字符串转换为数字数组，从右到左处理
            const digits = str.split('').map(Number);
            let carry = increment;
            
            // 从右到左进行加法运算
            for (let i = digits.length - 1; i >= 0 && carry > 0; i--) {
                const sum = digits[i] + carry;
                digits[i] = sum % 10;
                carry = Math.floor(sum / 10);
            }
            
            // 如果还有进位，在左侧添加
            if (carry > 0) {
                digits.unshift(carry);
            }
            
            return digits.join('');
        }
        // 生成条码
        function generateBarcodes() {
            // 直接使用字符串，避免parseInt精度丢失
            const startNumberStr = currentFormData.start_number;
            console.log(startNumberStr);
            const selectedType = currentFormData.inspection_type;
            const requiredLength = lengthLimits[selectedType];
            console.log(selectedType);
            
            barcodeImages = [];
            
            // 根据检验类型决定生成逻辑
            if (selectedType === '其他类型公证检验') {
                // 其他类型公证检验：根据选择的检测类型数量生成条码
                const detectionTypes = currentFormData.detection_types || [];
                console.log('检测类型:', detectionTypes);
                
                for (let i = 0; i < detectionTypes.length; i++) {
                    const detectionType = detectionTypes[i];
                    const prefix = detectionTypePrefixes[detectionType];
                    
                    if (prefix) {
                        // 在原始条码前添加两位数字前缀
                        const barcodeNumber = prefix + startNumberStr;
                        console.log(`生成条码 ${i + 1}: ${barcodeNumber} (前缀: ${prefix})`);
                        barcodeImages.push({
                            number: barcodeNumber,
                            filename: `barcode_${barcodeNumber}.png`,
                            detectionType: detectionType,
                            prefix: prefix
                        });
                    }
                }
            } else {
                // 其他检验类型：按照原有逻辑生成条码
                const barcodeCount = parseInt(currentFormData.barcode_count);
                console.log(barcodeCount);
                
                for (let i = 0; i < barcodeCount; i++) {
                    // 使用字符串递增函数，避免大数字精度丢失
                    const barcodeNumber = i === 0 ? startNumberStr : incrementStringNumber(startNumberStr, i);
                    console.log(barcodeNumber);
                    barcodeImages.push({
                        number: barcodeNumber,
                        filename: `barcode_${barcodeNumber}.png`
                    });
                }
            }
            
            console.log(barcodeImages);
            
            // 显示打印页面
            showPrintPage();
        }

        // 切换打印模式
        function switchPrintMode(mode) {
            currentPrintMode = mode;
            
            // 更新按钮状态
            document.getElementById('a4ModeBtn').classList.toggle('active', mode === 'a4');
            document.getElementById('tscModeBtn').classList.toggle('active', mode === 'tsc');
            if(mode === 'tsc'){
                document.getElementById('a4PreviewHeader').style.display = 'none';
            }else{
                document.getElementById('a4PreviewHeader').style.display = 'block';
            }
            // 重新生成打印内容
            generatePrintContent();
            
            // 如果选择TSC模式，自动初始化USB连接
            if (mode === 'tsc') {
                initTSCConnection();
            }
        }

        // 显示打印页面
        function showPrintPage() {
            document.getElementById('formContainer').style.display = 'none';
            document.getElementById('printContainer').style.display = 'block';
            
            // 生成打印内容
            generatePrintContent();
        }

        // 生成打印内容
        function generatePrintContent() {
            const printContent = document.getElementById('printContent');
            printContent.innerHTML = '';
            
            if (currentPrintMode === 'a4') {
                generateA4Content();
            } else if (currentPrintMode === 'tsc') {
                generateTSCContent();
            }
        }

        // 生成A4打印内容
        function generateA4Content() {
            const printContent = document.getElementById('printContent');
            
            
            const itemsPerPage = 10; // 每页10个条码
            const totalPages = Math.ceil(barcodeImages.length / itemsPerPage);
            
            for (let page = 0; page < totalPages; page++) {
                const pageDiv = document.createElement('div');
                pageDiv.className = 'a4-page';
                
                const startIndex = page * itemsPerPage;
                const endIndex = Math.min(startIndex + itemsPerPage, barcodeImages.length);
                const pageBarcodes = barcodeImages.slice(startIndex, endIndex);
                
                const gridDiv = document.createElement('div');
                gridDiv.className = 'a4-grid';
                
                pageBarcodes.forEach((barcode, index) => {
                    const card = document.createElement('div');
                    card.className = 'a4-card';
                    
                    card.innerHTML = `
                        <div class="barcode-info">
                            <div class="info-row">
                                <div class="info-group">
                                    <span class="barcode-info-label">批号:</span>
                                    <span>${currentFormData.batch_number}</span>
                                </div>
                                <div class="info-group">
                                    <span class="barcode-info-label">包号:</span>
                                    <span>${currentFormData.package_number}</span>
                                </div>
                            </div>
                            <div class="info-row">
                                <div class="info-group">
                                    <span class="barcode-info-label">产地:</span>
                                    <span>${currentFormData.origin}</span>
                                </div>
                                <div class="info-group">
                                    <span class="barcode-info-label">样品号:</span>
                                    <span>${currentFormData.sample_number}</span>
                                </div>
                            </div>
                            <div class="info-row">
                                <div class="info-group">
                                    <span class="barcode-info-label">日期:</span>
                                    <span>${currentFormData.sampling_date}</span>
                                </div>
                            </div>
                        </div>
                        <div class="barcode-image">
                            <svg id="a4-barcode-${page}-${index}"></svg>
                        </div>
                        <div class="barcode-number">${barcode.number}</div>
                    `;
                    
                    gridDiv.appendChild(card);
                });
                
                pageDiv.appendChild(gridDiv);
                printContent.appendChild(pageDiv);
                
                // 生成条码
                setTimeout(() => {
                    pageBarcodes.forEach((barcode, index) => {
                        JsBarcode(`#a4-barcode-${page}-${index}`, barcode.number, {
                            format: "CODE128",
                            width: 2,
                            height: 60,
                            displayValue: false,
                            margin: 2
                        });
                    });
                }, 100);
            }
        }

        // 生成条码标签内容
        function generateLabelContent() {
            const printContent = document.getElementById('printContent');
            
            // 创建标签容器（预览时使用flex布局，打印时会被覆盖）
            const labelContainer = document.createElement('div');
            labelContainer.className = 'label-container';
            labelContainer.style.cssText = 'display: flex; flex-wrap: wrap; gap: 10px; justify-content: center;';
            
            barcodeImages.forEach((barcode, index) => {
                const pageDiv = document.createElement('div');
                pageDiv.className = 'label-page';
                
                const card = document.createElement('div');
                card.className = 'label-card';
                
                card.innerHTML = `
                    <div class="barcode-info">
                        <div class="info-row">
                            <div class="info-group">
                                <span class="barcode-info-label">批号:</span>
                                <span style="font-weight: bold;">${currentFormData.batch_number}</span>
                            </div>
                            <div class="info-group">
                                <span class="barcode-info-label">包号:</span>
                                <span style="font-weight: bold;">${currentFormData.package_number}</span>
                            </div>
                        </div>
                        <div class="info-row">
                            <div class="info-group">
                                <span class="barcode-info-label">产地:</span>
                                <span>${currentFormData.origin}</span>
                            </div>
                            <div class="info-group">
                                <span class="barcode-info-label">样品号:</span>
                                <span>${currentFormData.sample_number}</span>
                            </div>
                        </div>
                        <div class="info-row">
                            <div class="info-group">
                                <span class="barcode-info-label">日期:</span>
                                <span>${currentFormData.sampling_date}</span>
                            </div>
                        </div>
                    </div>
                    <div class="barcode-image">
                        <svg id="label-barcode-${index}"></svg>
                    </div>
                    <div class="barcode-number">${barcode.number}</div>
                `;
                
                pageDiv.appendChild(card);
                labelContainer.appendChild(pageDiv);
                
                // 生成条码 - TSC TTP-244M Pro优化参数
                setTimeout(() => {
                    JsBarcode(`#label-barcode-${index}`, barcode.number, {
                        format: "CODE128",
                        width: 1.3,           // 增加条码线宽，提高扫描成功率
                        height: 28,           // 增加条码高度，提高可读性
                        displayValue: false,  // 不显示文字，单独处理
                        margin: 1,            // 减少静区，充分利用空间
                        fontSize: 9,          // 字体大小
                        fontFamily: "monospace" // 等宽字体
                    });
                }, 100);
            });
            
            printContent.appendChild(labelContainer);
        }

        // 初始化TSC打印机连接
        function initTSCConnection() {
            // 获取USB打印机列表
            var obj = {"usb_list": []};
            websocket_connection(obj);
            
            // 获取驱动打印机列表
            var obj2 = {"driver_list": []};
            websocket_connection(obj2);
        }
        
        // TSC WebSocket连接
        function websocket_connection(obj) {
            var websocket = new WebSocket(url);
            websocket.onopen = function(e) {
                websocket.send(JSON.stringify(obj));
            };

            websocket.onmessage = function(event) {
                if(event.data == "Finished") {
                    websocket.close();
                } else {
                    try {
                        const response = JSON.parse(event.data);
                        if ('usb_list' in response) {
                            usb_printers = response.usb_list;
                            console.log('USB打印机列表:', usb_printers);
                            // 如果当前是TSC模式，检查连接状态
                            if (currentPrintMode === 'tsc') {
                                autoConnectUSB();
                            }
                        }
                        if ('driver_list' in response) {
                            driver_printers = response.driver_list;
                            console.log('驱动打印机列表:', driver_printers);
                        }
                        if ('Function_Failed' in response) {
                            alert(`TSC打印机操作失败: ${response.Function_Failed}`);
                        }
                    } catch (e) {
                        console.error('TSC响应解析失败:', e);
                    }
                }
            };

            websocket.onclose = function(event) {
                if (event.code != 1000) {
                    console.error('TSC WebSocket连接关闭:', event.code);
                    // 如果当前是TSC模式且连接失败，显示错误信息
                    if (currentPrintMode === 'tsc') {
                        setTimeout(() => {
                            if (usb_printers.length === 0) {
                                document.getElementById('tscConnectionStatus').style.display = 'none';
                                document.getElementById('tscPrinterInfo').style.display = 'none';
                                document.getElementById('tscErrorInfo').style.display = 'block';
                            }
                        }, 3000);
                    }
                }
            };

            websocket.onerror = function(error) {
                console.error('TSC WebSocket错误:', error);
                // 如果当前是TSC模式且连接错误，显示错误信息
                if (currentPrintMode === 'tsc') {
                    setTimeout(() => {
                        if (usb_printers.length === 0) {
                            document.getElementById('tscConnectionStatus').style.display = 'none';
                            document.getElementById('tscPrinterInfo').style.display = 'none';
                            document.getElementById('tscErrorInfo').style.display = 'block';
                        }
                    }, 3000);
                }
            };
        }
        
        // 生成TSC打印内容
        function generateTSCContent() {
            const printContent = document.getElementById('printContent');
            printContent.innerHTML = `
                <div style="text-align: center; padding: 20px;">
                    <h3>TSC打印机模式</h3>
                    <div id="tscConnectionStatus" style="margin: 20px 0;">
                        <p>正在连接USB打印机...</p>
                        <div class="loading-spinner" style="display: inline-block; width: 20px; height: 20px; border: 2px solid #f3f3f3; border-top: 2px solid #1a6dcc; border-radius: 50%; animation: spin 1s linear infinite;"></div>
                    </div>
                    <div id="tscPrinterInfo" style="display: none;">
                        <p>已连接: <span id="selectedPrinterInfo"></span></p>
                        <div style="margin: 20px 0;display: flex;justify-content: center;">
                            <button onclick="printWithTSC()" class="btn btn-primary">
                                <i class="fas fa-print"></i> 开始打印
                            </button>
                        </div>
                        
                    </div>
                    <div id="tscErrorInfo" style="display: none; color: #ff4444;">
                        <p>连接失败，请检查TSC PrintServer是否正在运行</p>
                        <button onclick="retryTSCConnection()" class="btn btn-secondary">
                            <i class="fas fa-redo"></i> 重试连接
                        </button>
                    </div>
                </div>
            `;
            
            // 自动尝试USB连接
            setTimeout(() => {
                autoConnectUSB();
            }, 1000);
        }
        
        // 选择TSC打印机
        function selectTSCPrinter(type) {
            selectedConnectionType = type;
            
            if (type === 'usb') {
                if (usb_printers.length > 0) {
                    selectedPrinter = usb_printers[0];
                    document.getElementById('selectedPrinterInfo').textContent = 
                        `USB: ${selectedPrinter.USBName}`;
                    document.getElementById('printerInfo').style.display = 'block';
                } else {
                    alert('未找到USB打印机，请确保TSC PrintServer正在运行');
                }
            } else if (type === 'driver') {
                if (driver_printers.length > 0) {
                    selectedPrinter = driver_printers[0];
                    document.getElementById('selectedPrinterInfo').textContent = 
                        `驱动: ${selectedPrinter.DriverName}`;
                    document.getElementById('printerInfo').style.display = 'block';
                } else {
                    alert('未找到驱动打印机');
                }
            }
        }
        
        // 使用TSC打印机打印
        function printWithTSC() {
            if (!selectedPrinter) {
                alert('请先选择打印机');
                return;
            }
            
            console.log('开始TSC打印，条码数量:', barcodeImages.length);
            
            // 初始化并连接打印机
            init();
            if (selectedConnectionType === 'usb') {
                openport_usb(selectedPrinter.USBPath);
            } else if (selectedConnectionType === 'driver') {
                openport_driver(selectedPrinter.DriverName);
            }
            
            // 设置80mm×45mm标签尺寸
            // setup("80", "45", "4", "8", "0", "3", "0");
            
            // 逐个处理每个条码
            barcodeImages.forEach((barcodeData, index) => {
                console.log(`处理第${index + 1}个条码:`, barcodeData.number);
                
                // 清空缓冲区
                clearbuffer();
                
                // 添加文字信息
                windowsfont("140", "10", "32", "0", "2", "0", "Arial", "棉花粘性（含糖）检测方法试点检验样品");
                
                // 添加条码
                barcode("150", "80", "128", "120", "2", "0", "3.8", "3", barcodeData.number);
                
                // 添加检测类型信息
                if (barcodeData.detectionType) {
                    windowsfont("320", "250", "24", "0", "2", "0", "Arial", `检测类型: ${barcodeData.detectionType}`);
                }
                
                // 打印标签
                printlabel(1, 1);
            });
            
            closeport();
            
            // 发送所有打印指令
            var obj = {"functions_inorder": functions_inorder};
            console.log('TSC打印指令:', obj);
            websocket_connection(obj);
            
            alert('TSC打印任务已发送');
        }
        
        // 返回表单页面
        function backToForm() {
            document.getElementById('printContainer').style.display = 'none';
            document.getElementById('formContainer').style.display = 'block';
        }

        // 下载PDF
        async function downloadPDF() {
            const { jsPDF } = window.jspdf;
            
            try {
                if (currentPrintMode === 'a4') {
                    // A4模式PDF
                    const pdf = new jsPDF('p', 'mm', 'a4');
                    const printContent = document.getElementById('printContent');
                    const pages = printContent.querySelectorAll('.a4-page');
                    
                    for (let i = 0; i < pages.length; i++) {
                        if (i > 0) {
                            pdf.addPage();
                        }
                        
                        const canvas = await html2canvas(pages[i], {
                            scale: 2,
                            useCORS: true,
                            allowTaint: true
                        });
                        
                        const imgData = canvas.toDataURL('image/png');
                        const imgWidth = 210; // A4宽度
                        const imgHeight = (canvas.height * imgWidth) / canvas.width;
                        
                        pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
                    }
                } else {
                    // 条码标签模式PDF
                    const pdf = new jsPDF('p', 'mm', [75, 45]);
                    const printContent = document.getElementById('printContent');
                    const pages = printContent.querySelectorAll('.label-page');
                    
                    for (let i = 0; i < pages.length; i++) {
                        if (i > 0) {
                            pdf.addPage([75, 45]);
                        }
                        
                        const canvas = await html2canvas(pages[i], {
                            scale: 2,
                            useCORS: true,
                            allowTaint: true
                        });
                        
                        const imgData = canvas.toDataURL('image/png');
                        pdf.addImage(imgData, 'PNG', 0, 0, 75, 45);
                    }
                }
                
                pdf.save('barcodes.pdf');
            } catch (error) {
                console.error('PDF生成失败:', error);
                alert('PDF生成失败，请重试');
            }
        }

        // 自动USB连接
        function autoConnectUSB() {
            selectedConnectionType = 'usb';
            
            // 检查USB打印机列表
            if (usb_printers.length > 0) {
                selectedPrinter = usb_printers[0];
                document.getElementById('selectedPrinterInfo').textContent = 
                    `USB: ${selectedPrinter.USBName}`;
                document.getElementById('tscConnectionStatus').style.display = 'none';
                document.getElementById('tscPrinterInfo').style.display = 'block';
                document.getElementById('tscErrorInfo').style.display = 'none';
            } else {
                // 如果还没有获取到打印机列表，等待一下再检查
                setTimeout(() => {
                    if (usb_printers.length > 0) {
                        selectedPrinter = usb_printers[0];
                        document.getElementById('selectedPrinterInfo').textContent = 
                            `USB: ${selectedPrinter.USBName}`;
                        document.getElementById('tscConnectionStatus').style.display = 'none';
                        document.getElementById('tscPrinterInfo').style.display = 'block';
                        document.getElementById('tscErrorInfo').style.display = 'none';
                    } else {
                        // 连接失败
                        document.getElementById('tscConnectionStatus').style.display = 'none';
                        document.getElementById('tscPrinterInfo').style.display = 'none';
                        document.getElementById('tscErrorInfo').style.display = 'block';
                    }
                }, 2000);
            }
        }
        
        // 重试TSC连接
        function retryTSCConnection() {
            document.getElementById('tscConnectionStatus').style.display = 'block';
            document.getElementById('tscPrinterInfo').style.display = 'none';
            document.getElementById('tscErrorInfo').style.display = 'none';
            
            // 重新初始化连接
            initTSCConnection();
            
            // 延迟检查连接结果
            setTimeout(() => {
                autoConnectUSB();
            }, 2000);
        }
    </script>
</body>
</html> 